package com.fs.sys.entityservice.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fs.sys.bean.dto.AppCategoryDTO;
import com.fs.sys.bean.dto.AppDTO;
import com.fs.sys.bean.query.AppQuery;
import com.fs.sys.domain.entity.AppEntity;
import com.fs.sys.domain.mapper.AppMapper;
import com.fs.sys.entityservice.AppCategoryEntityService;
import com.fs.sys.entityservice.AppEntityService;
import com.fs.common.base.service.AbstractBaseEntityService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 应用服务实现 
 * @author Coder Generator 2025-06-06 11:03:07 
 **/
@Service
public class AppEntityServiceImpl extends AbstractBaseEntityService<AppEntity, AppDTO, AppMapper, AppQuery> implements AppEntityService {
    @Autowired
    private AppCategoryEntityService categoryEntityService;

    @Override
    protected QueryWrapper<AppEntity> queryToWrapper(AppQuery query) {
        return this.createQueryWrapper()
                .eq(StringUtils.isNotBlank(query.getId()), "id", query.getId())
                .in(null != query.getIds(), "id", query.getIds())
                .eq(StringUtils.isNotBlank(query.getCode()), "code", query.getCode())
                .eq(StringUtils.isNotBlank(query.getTenantId()), "tenant_id", query.getTenantId())
                .eq(null != query.getUseLimitType(), "use_limit_type", query.getUseLimitType())
                .ne(StringUtils.isNotBlank(query.getCodeNot()), "code", query.getCodeNot())
                .orderByDesc("create_time");
    }

    /**
     * 如果在在租户编号时，是否需要根据租户编号进行筛选
     *
     * @return 是否根据租户编号筛选数据
     */
    @Override
    protected boolean filterByTenant() {
        // 应用的查询不能自动根据租户id过滤
        return false;
    }

    /**
     * 查询后处理
     *
     * @param list 查询结果
     */
    @Override
    protected void processAfterQuery(List<AppDTO> list) {
        super.processAfterQuery(list);
        // 补充分类名称
        if (CollectionUtils.isEmpty(list)) {
            return;
        }

        List<String> categoryIds = list.stream()
                .map(AppDTO::getCategoryId)
                .filter(Objects::nonNull)
                .toList();
        if (!CollectionUtils.isEmpty(categoryIds)) {
            Map<String, String> categoryMap = categoryEntityService.findByIds(categoryIds)
                    .stream()
                    .collect(Collectors.toMap(AppCategoryDTO::getId, AppCategoryDTO::getName));
            list.forEach(item -> {
                if (StringUtils.isBlank(item.getCategoryId())) {
                    return;
                }

                item.setCategoryName(categoryMap.get(item.getCategoryId()));
            });
        }
    }
}